/*
 * 使用 synchronized + wait + notify 可以实现线程的交替 run/sleep
 * 但是不能2个线程同时运行
 */

package org.wzq.learn;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class ProducerConsumer {
    volatile List<String> container = new ArrayList<String>();
    private final int capacity = 5;

    public synchronized void produce() {
        while (true) {
            while (container.size() == capacity) {
                try {
                    System.out.println("full wait");
                    notifyAll();
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // awaken
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("produce");
            container.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        }
    }

    public synchronized void consume() {
        while (true) {
            while (container.size() == 0) {
                try {
                    System.out.println("empty wait");
                    notifyAll();
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // awaken
            String s = container.remove(0);
            System.out.println("consume " + s);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ProducerConsumer p = new ProducerConsumer();
        new Thread(p::consume).start();
        new Thread(p::produce).start();
    }

}
